<script setup lang="tsx">
import { PAGING } from '@/constant'
import { TANPANCHA_STATUS } from '@/constant/modules/tanpancha'
import { Search } from '@element-plus/icons-vue'
import type { TableColumn, CarbonInventory } from '@/types'
import PanchaInformation from './components/pancha-information/index.vue'
import PanchaTpl from './components/pancha-tpl/index.vue'

import { carbonInventoryApi } from '@/api'

defineOptions({ name: 'TanpanchaLists' })

const panchaTplRef = ref<InstanceType<typeof PanchaTpl>>()

const loading = ref(false)
const panchaType = ref<0 | 1>(0)
const tableData = shallowRef<CarbonInventory[]>([])
const pagination = reactive({
  pageNumber: PAGING.PARAMS.pageNumber,
  pageSize: PAGING.PARAMS.pageSize,
  total: 0,
})
const tanpanchaStore = useTanpanchaStore()
const protocol = ref()
const year = ref()
const point = ref()

const readonly = ref(false)
const lockCarbonInventory = ref(false)

const templateId = ref()

const isReady = ref(false)
const showPanchaInformation = ref(false)

const protocolCode = ref()
const dataTime = ref()
const pointId = ref()

const unit = computed(() => {
  return tanpanchaStore.panchaUnit
})
const columns = computed<TableColumn<CarbonInventory>[]>(() => {
  return [
    {
      key: uuid(),
      label: '核算主体',
      prop: 'pointFullName',
    },
    {
      key: uuid(),
      label: '核算标准',
      prop: 'protocolCode',
    },
    {
      key: uuid(),
      label: '核算时间',
      prop: 'dataTime',
    },
    {
      key: uuid(),
      label: '状态',
      prop: 'status',
      render({ row }) {
        return (
          <span>{tanpanchaStore.getPanchaStatusText(row.status)}</span>
        )
      },
    },
    {
      key: uuid(),
      label: `总碳排放量（${unit.value}）`,
      prop: 'totalCarbonEmission',
      minWidth: 150,
    },
    {
      key: uuid(),
      label: `用能排放（${unit.value}）`,
      prop: 'carbonEmission',
      minWidth: 150,
    },
    {
      key: uuid(),
      label: `绿色减排（${unit.value}）`,
      prop: 'emissionReduction',
      minWidth: 150,
    },
    {
      key: uuid(),
      label: '核算人',
      prop: 'creationName',
    },
    {
      key: uuid(),
      label: '更新时间',
      prop: 'updateTime',
    },
  ]
})

async function handleClickNode(node: any) {
  point.value = node.id
  await nextTick()
  await getTableData()
  isReady.value = true
}

async function getTableData() {
  loading.value = true
  try {
    const { data } = await carbonInventoryApi.queryCarbonInventoryList({
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize,
      protocolCode: unref(protocol),
      dataTime: unref(year),
      pointId: unref(point),
    })
    tableData.value = data.records ?? []
    pagination.total = data.total ?? 0
  }
  finally {
    loading.value = false
  }
}

async function clickSearch() {
  pagination.pageNumber = 1
  await nextTick()
  getTableData()
}

// 点击新增
async function clickAdd() {
  readonly.value = false
  lockCarbonInventory.value = false

  panchaType.value = 0
  protocolCode.value = unref(protocol)
  dataTime.value = unref(year)
  pointId.value = unref(point)
  await nextTick()
  showPanchaInformation.value = true
}

// 点击通过模板新增
async function clickAddByTpl() {
  readonly.value = false
  lockCarbonInventory.value = false

  panchaType.value = 1
  protocolCode.value = unref(protocol)
  dataTime.value = unref(year)
  pointId.value = unref(point)
  await nextTick()
  panchaTplRef.value?.open()
}

// 删除
async function handleDeleteCarbonInventory(row: CarbonInventory) {
  const res = await ElMessageBox.confirm('是否删除该盘查？', '操作提示').catch(() => {})
  if (res && res === 'confirm') {
    carbonInventoryApi.deleteCarbonInventoryById(row.id).then(() => {
      ElMessage.success('删除成功')
      clickSearch()
    })
  }
}

// 查看
async function handleViewCarbonInventory(row: CarbonInventory) {
  readonly.value = true
  lockCarbonInventory.value = true

  // 查看的是盘查，可能存在的模板ID要清除
  templateId.value = undefined

  protocolCode.value = row.protocolCode
  dataTime.value = `${row.dataTime}`
  pointId.value = row.pointId
  await nextTick()
  showPanchaInformation.value = true
}

// 填报
async function handleEditCarbonInventory(row: CarbonInventory) {
  readonly.value = false
  lockCarbonInventory.value = true

  // 填报（修改）的是盘查，可能存在的模板ID要清除
  templateId.value = undefined

  protocolCode.value = row.protocolCode
  dataTime.value = `${row.dataTime}`
  pointId.value = row.pointId
  await nextTick()
  showPanchaInformation.value = true
}

// 归档
async function handleArchiveCarbonInventory(row: CarbonInventory) {
  carbonInventoryApi.archiveCarbonInventoryById(row.id).then(() => {
    ElMessage.success('操作成功')
    getTableData()
  })
}

// 撤销归档
async function handleUnArchiveCarbonInventory(row: CarbonInventory) {
  carbonInventoryApi.cancelCarbonInventoryById(row.id).then(() => {
    ElMessage.success('操作成功')
    getTableData()
  })
}

async function handleSelectedTpl(data: any) {
  // 使用模板的协议和主体，ID
  templateId.value = data.id
  pointId.value = data.pointId
  protocolCode.value = data.protocolCode
  await nextTick()
  showPanchaInformation.value = true
}

watch([() => showPanchaInformation.value], () => {
  if (showPanchaInformation.value === false) {
    clickSearch()
  }
})
</script>

<template>
  <div class="padding-sm flex container">
    <ReadonlyPointTree
      fire
      :need-full-name="1"
      class="flex-incompressible"
      @click-node="handleClickNode"
    />
    <div
      class="flex-direction flex-fillRemaining margin-left-sm overflow flex align-end"
    >
      <view-table
        :loading="loading"
        :columns="columns"
        :data="tableData"
        :show-toolbox="false"
        border
        row-key="id"
        :operate-width="260"
      >
        <template #actions>
          <ElForm inline>
            <ElFormItem label="核算标准">
              <ElSelect v-model="protocol" clearable placeholder="请选择标准">
                <ElOption
                  v-for="item in tanpanchaStore.standards"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="核算时间">
              <ElDatePicker
                v-model="year"
                :editable="false"
                clearable
                type="year"
                placeholder="选择日期"
                format="YYYY"
                value-format="YYYY"
              />
            </ElFormItem>
            <ElFormItem>
              <ElButton
                type="primary"
                :icon="Search"
                @click="clickSearch"
              >
                查询
              </ElButton>
              <ElButton type="success" @click="clickAdd">
                新增
              </ElButton>
              <ElButton type="warning" @click="clickAddByTpl">
                通过模板新增
              </ElButton>
            </ElFormItem>
          </ElForm>
        </template>
        <template #operate="{ row }">
          <ElButton type="warning" size="small" @click="handleViewCarbonInventory(row)">
            查看
          </ElButton>
          <template v-if="row.status === TANPANCHA_STATUS.REPORTED">
            <ElButton type="primary" size="small" @click="handleEditCarbonInventory(row)">
              填报
            </ElButton>
            <ElButton type="success" size="small" @click="handleArchiveCarbonInventory(row)">
              归档
            </ElButton>
            <ElButton type="danger" size="small" @click="handleDeleteCarbonInventory(row)">
              删除
            </ElButton>
          </template>
          <template v-else-if="row.status === TANPANCHA_STATUS.ARCHIVED">
            <ElButton type="info" size="small" @click="handleUnArchiveCarbonInventory(row)">
              撤销归档
            </ElButton>
          </template>
        </template>
      </view-table>

      <!-- 分页 -->
      <ListsPagination
        v-model:page-num="pagination.pageNumber"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        @current-change="getTableData"
        @size-change="getTableData"
      />
    </div>
    <PanchaInformation
      v-if="showPanchaInformation"
      v-model="showPanchaInformation"
      :initial-protocol="protocolCode"
      :initial-year="dataTime"
      :initial-point="pointId"
      :type="panchaType"
      :readonly="readonly"
      :lock-carbon-inventory="lockCarbonInventory"
      :template-id="templateId"
      @destroy-template-id="templateId = undefined"
    />
    <PanchaTpl
      v-if="isReady && point" ref="panchaTplRef"
      :initial-point="point" :initial-protocol="protocol"
      @selected="handleSelectedTpl"
    />
  </div>
</template>
